package com.demo.webapp.views.freemarker.directive.core;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.demo.webapp.service.AccessStatisticsService;
import com.demo.webapp.service.AccessStatisticsService.TYPE;

import freemarker.core.Environment;
import freemarker.core.Environment.TemplateDirectiveBodyEx;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

/**
 * 自定义指令: 访问统计
 * @author ryuu.kk
 *
 */
public class RecordDirective extends PageContextDirectiveSupport {

	/**
	 * 访问统计服务
	 */
	@Autowired
	private AccessStatisticsService accessStatisticsService;
	
	@Override
	public void preWriter(Environment env, TemplateDirectiveBodyEx bodyEx,
			TemplateModel[] loopVars, SimpleHash hash, Map params)
			throws IOException, TemplateException {
		Long id = null;
		String name = "";
		//int type = 0x01;
		String path = "";
		
		id = getLong("id", params);
		name = getString("name", params, getDefaultValue("name"));
//		if (id == null) {
//			throw new TemplateException("自定义指令core_record的id不能为空", env);
//		}
		// 取得读信息
		int count = 0 ;		
		count = accessStatisticsService.count(id, TYPE.READ);
		hash.put("count", count);
		hash.put("id", id);
		hash.put("name", name);
	}

	@Override
	public String getTemplatePath(Map params) {
		String path = "";
		try {
			path = getString("path", params, "");
		} catch (TemplateModelException e) {}
		return path;
	}

	@Override
	public void afterInvoke(Writer writer) {
		// TODO Auto-generated method stub
	}


}
